# 导入系统资源模
from ascript.ios.system import R,device
# 导入动作模块
from ascript.ios import action
# 导入节点检索模块
from ascript.ios import node
# 导入图色检索模块
from ascript.ios import screen
from ascript.ios import system
from ascript.ios import media
from ascript.ios.screen import Ocr
from ascript.ios.screen import FindImages
import requests
import time

res = system.app_state(bundle_id="com.tencent.xin")
if res is not True:
    # 根据包名启动,推荐使用
    system.app_start(bundle_id="com.tencent.xin")

uuid = device.get_device_id()

while True:
    time.sleep(2)
    # 获取任务
    ocr_res = Ocr(rect =[0,0,750,1336]).paddleocr_v3()
    if ocr_res:
        found = False
        for r in ocr_res:
            if r['text'] == '扫-扫':
                found = True
                break
        if not found:
            action.click(470.0,1309.0)

    r = requests.get(f"http://192.168.10.95:9999/api/task.process/pull?uuid={uuid}")
    res_format_data = r.json()
    if res_format_data["code"] == 200:
        print("qrcode is", res_format_data['data']['qrcode'])
        qrcode_name =  res_format_data['data']['qrcode']
        qrcode_url = f"http://192.168.10.95:9999/qrcode/{qrcode_name}"
        print("qrcode url is:", qrcode_url)
        r = requests.get(qrcode_url)
        # 保存文件至res下的tpl.png
        with open (R.assets("tpl.png"), 'wb') as f:
            f.write(r.content)

        # 将图片保存到相册
        res = media.save_pic2photo(qrcode_url)

        if res == "success":
            action.click(161.0,553.0)
            # 暂停3s
            time.sleep(1)
            # 打开选择相册，相册的坐标
            action.click(640, 1049)
            # 打开相册后，找到最新二维码的位置
            time.sleep(2)
            print(R.assets("tpl.png"))
            find_res = FindImages([R.assets("tpl.png"),] ,confidence= 0.10).find()
            print("Find images result is:", find_res)
            if find_res:
                action.click(find_res["center_x"], find_res["center_y"])

            time.sleep(1)

            # 二维码确定页面，“完成”按钮的坐标
            action.click(655.5,86.0)

            time.sleep(10)
            # 小程序的关闭按钮的坐标
            action.click(725, 50)

        else:
            print("存入失败:"+res)
